package com.sdutcm.Controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.security.PublicKey;
import java.util.Map;

/*
 *@Author Yan
 *@Create 2019-08-28 11:22
 */
@Controller
public class LoginController {

    @GetMapping("/login")
    public String loginShow() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, Model map) {
        System.out.println(username);
        Subject subject = SecurityUtils.getSubject();
        String dbpassword = new Md5Hash(password,username).toString();
        UsernamePasswordToken token = new UsernamePasswordToken(username,dbpassword);


        try {
            subject.login(token);
        }catch (IncorrectCredentialsException e1){
            map.addAttribute("msg","密码不正确");
        }catch (UnknownAccountException e2){
            map.addAttribute("msg","账号不存在");
        }catch (AuthenticationException e3){
            map.addAttribute("msg","状态不正常");
        }
        if (subject.isAuthenticated()){
            System.out.println("认证成功");
            map.addAttribute("username",username);
            return "index";
        }else {
            return "login";
        }


    }


    @GetMapping("/logout")
    public String logout(Model model) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("msg","安全退出！");
        return "login";
    }

//    密码转换
//    public static void main(String[] args) {
//        String dbpassword = new Md5Hash("1234","user").toString();
//        System.out.println(dbpassword);
//    }

}
